
package com.myproject0616chat;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Server {
	
	private List<Socket> clients = new ArrayList<>();

	public Server() throws IOException {
		new Thread(new Runnable() {
			ServerSocket server = new ServerSocket(22222);

			@Override
			public void run() {
				while (true) {
					try {
						Socket socket = server.accept();
					
						System.out.println(socket.getInetAddress().getHostAddress());
						clients.add(socket);
						sendMessage(socket.getInetAddress().getHostAddress() + " 进入聊天室！\n");
						Receiver receiver = new Receiver(socket);
						receiver.start();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	public void sendMessage(String message) {
		for (Socket socket : clients) {
			try {
				ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
				oos.writeObject(message + "\n");
				oos.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		System.out.println("服务器启动成功");
		new Server();
	}

	class Receiver extends Thread {
		private Socket socket;

		public Receiver(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			while (true) {
				try {
					ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
					String message = (String) ois.readObject();
					SimpleDateFormat c = new SimpleDateFormat("YYYY年MM月dd日hh:mm:ss");
					String s = c.format(new Date());
					message = s + "\n" + socket.getInetAddress().getHostAddress() + "：\n" + message + "\n";
					System.out.println(message);
					sendMessage(message);
				} catch (Exception e) {
					if (e.getMessage().equals("Connection reset")) {
						clients.remove(socket);
						System.out.println(socket.getInetAddress().getHostAddress() + " 离开了！");
						sendMessage(socket.getInetAddress().getHostAddress() + " 离开了！\n");
						break;
              
					}
				}
			}
		}
	}
}
